package com.example.zhongshuishi.controller;


import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.example.zhongshuishi.entity.CustomerUserDetails;
import com.example.zhongshuishi.entity.PersonnelDto;
import com.example.zhongshuishi.entity.StudentDto;
import com.example.zhongshuishi.service.PersonnelService;
import com.example.zhongshuishi.service.SmsService;
import com.example.zhongshuishi.service.StudentService;
import com.example.zhongshuishi.utils.JwtTokenUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 鑳℃垬纾�
 * @version 1.0
 * @description TODO
 * @date 2025/3/29 9:23
 */
@RestController
@RequestMapping("/api/login")
public class LogginController {

    @Autowired
    private PersonnelService personnelService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @PostMapping("/teacher")
    public ResponseEntity logginTeacher(@NotNull String phone, @NotNull(message = "验证码不能为空")  String code, HttpServletRequest httpServletRequest, HttpServletResponse response) throws IOException {
        try {
            //验证sms
            boolean b = smsService.verifyCode(phone, code);
            if(!b){
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("验证码错误");
            }

            PersonnelDto personnelDto = personnelService.selectByPhone(phone);
            if(personnelDto != null){
                //session
                HttpSession session = httpServletRequest.getSession();
                session.setAttribute("user",personnelDto);
                session.setMaxInactiveInterval(30*60);//30分钟
                response.setHeader("teacher",phone);
                Cookie cookie = new Cookie("teacher", phone);
                cookie.setMaxAge(60 * 30);
                cookie.setHttpOnly(true);
                cookie.setSecure(true);
                response.addCookie(cookie);

                //token
                String token = jwtTokenUtil.generateToken(personnelDto.getId().toString(),personnelDto.getUndertaker(),phone,"teacher");
                Map<String, String> tokenMap = new HashMap<>();
                tokenMap.put("token", token);
                tokenMap.put("tokenHeader", tokenHeader);
                tokenMap.put("tokenHead", tokenHead);
                return ResponseEntity.ok(tokenMap);
            }else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户不存在");
            }
        }catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }

    }

    @PostMapping("/student")
    public ResponseEntity logginSudent(@NotNull String phone,  @NotNull(message = "验证码不能为空") String code,HttpServletRequest httpServletRequest, HttpServletResponse response){
        try{
            //验证sms
            boolean b = smsService.verifyCode(phone, code);
            if(!b){
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("验证码错误");
            }

            StudentDto studentDto = studentService.getStudentByPhone(phone);
            if(studentDto == null){
                StudentDto studentDtoParam = new StudentDto();
                studentDtoParam.setStuPhone(phone);
                studentService.addStudent(studentDtoParam);
                studentDto = studentDtoParam;
            }
            //session
            HttpSession session = httpServletRequest.getSession();
            session.setAttribute("user",studentDto);
            session.setMaxInactiveInterval(30*60);//30分钟
            response.setHeader("student",phone);
            Cookie cookie = new Cookie("student", phone);
            cookie.setMaxAge(60 * 30);
            cookie.setHttpOnly(true);
            cookie.setSecure(true);
            response.addCookie(cookie);
            //token
            String token = jwtTokenUtil.generateToken(studentDto.getId(),studentDto.getStuName(),phone,"student");
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", token);
            tokenMap.put("tokenHeader", tokenHeader);
            tokenMap.put("tokenHead", tokenHead);
            return ResponseEntity.ok(tokenMap);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);

        }
    }

    @PostMapping("/out")
    public ResponseEntity logginOut(HttpServletRequest httpServletRequest, HttpServletResponse response){
        try{
            httpServletRequest.getSession().invalidate();
            return ResponseEntity.ok("已退出登录");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);

        }
    }

}
